import React, { useState } from "react";
import { Card, Steps, Button, List, Avatar, Space, Tag, message, Form, Input, Select, DatePicker } from "antd";
import { UserOutlined, SolutionOutlined, CalendarOutlined, ArrowRightOutlined, UserAddOutlined, ClockCircleOutlined, FileTextOutlined } from "@ant-design/icons";
import type { Department, Doctor, DoctorSchedule, AppointmentSlot, AppointmentFormData } from "../../types/appointment";
import { patientAPI } from "../../services/patient";
import Layout from "../../components/Layout";

// 苹果系统颜色常量
const APPLE_COLORS = {
  primary: '#007AFF',
  secondary: '#5856D6',
  success: '#34C759',
  warning: '#FF9500',
  danger: '#FF3B30',
  info: '#5AC8FA',
  lightGray: '#F2F2F7',
  mediumGray: '#C7C7CC',
  darkGray: '#8E8E93',
  text: '#000000',
  textSecondary: '#3C3C43',
  background: '#F2F2F7',
  cardBackground: '#FFFFFF'
};

const { Step } = Steps;

// Mock科室
const departments: Department[] = [
  { id: 'd1', name: '骨科' },
  { id: 'd2', name: '康复科' },
  { id: 'd3', name: '神经内科' }
];

// Mock排班
const doctorSchedules: DoctorSchedule[] = [
  { date: '2024-06-01', periods: [
    { period: 'morning', available: true, timeSlots: ['08:00', '08:30'] },
    { period: 'afternoon', available: false, timeSlots: [] }
  ] },
  { date: '2024-06-02', periods: [
    { period: 'morning', available: true, timeSlots: ['09:00', '09:30', '10:00'] },
    { period: 'afternoon', available: true, timeSlots: ['14:00', '14:30'] }
  ] }
];

// Mock医生
const doctors: Doctor[] = [
  { id: 'doc1', name: '王医生', departmentId: 'd1', title: '主任医师', schedule: doctorSchedules },
  { id: 'doc2', name: '李医生', departmentId: 'd2', title: '副主任医师', schedule: doctorSchedules },
  { id: 'doc3', name: '张医生', departmentId: 'd1', title: '主治医师', schedule: doctorSchedules }
];

const RegisterAppointment: React.FC = () => {
  const [current, setCurrent] = useState(0);
  const [form] = Form.useForm<AppointmentFormData>();
  // 选中科室、医生、时间
  const [selectedDepartment, setSelectedDepartment] = useState<string | null>(null);
  const [selectedDoctor, setSelectedDoctor] = useState<string | null>(null);
  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [selectedPeriod, setSelectedPeriod] = useState<'morning' | 'afternoon' | 'evening' | null>(null);
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<string | null>(null);

  const next = async () => {
    if (current === 0 && !selectedDepartment) {
      message.warning("请选择科室"); return;
    }
    if (current === 1 && !selectedDoctor) {
      message.warning("请选择医生"); return;
    }
    if (current === 2 && !(selectedDate && selectedPeriod && selectedTimeSlot)) {
      message.warning("请选择预约时间"); return;
    }
    if (current === 3) {
      try {
        const values = await form.validateFields();
        const appointmentData = {
          ...values,
          departmentId: selectedDepartment!,
          doctorId: selectedDoctor!,
          slot: {
            date: selectedDate!,
            period: selectedPeriod!,
            time: selectedTimeSlot!,
            doctorId: selectedDoctor!,
            departmentId: selectedDepartment!
          }
        };
        
        // 模拟环境下，使用本地模拟提交逻辑，避免API调用失败
        // 实际项目中会使用真实API调用
        // await patientAPI.createAppointment(appointmentData);
        
        // 模拟成功提交
        console.log('预约数据提交:', appointmentData);
        
        // 显示成功消息
        message.success("预约成功！您的预约号为：" + Date.now().toString().slice(-6));
        
        // 延迟后重置表单和状态，让用户有时间看到成功提示
        setTimeout(() => {
          resetState();
        }, 2000);
      } catch (error) {
        console.error('预约失败:', error);
        message.error("预约失败，请重试");
        return;
      }
    }
    setCurrent(v => v + 1);
  };
  
  const resetState = () => {
    setCurrent(0);
    setSelectedDepartment(null);
    setSelectedDoctor(null);
    setSelectedDate(null);
    setSelectedPeriod(null);
    setSelectedTimeSlot(null);
    form.resetFields();
  };
  const prev = () => setCurrent(v => v - 1);

  // 过滤当前科室的医生
  const filteredDoctors = doctors.filter(doc => doc.departmentId === selectedDepartment);

  return (
    <Layout title="预约挂号" showBackButton={true}>
      <div className="appointment-container">
        <div className="page-header">
          <h1 className="page-title">预约挂号</h1>
        </div>
        
        <Card className="apple-card appointment-flow-card" style={{ 
          borderRadius: 12, 
          boxShadow: '0 4px 16px rgba(0, 0, 0, 0.08)',
          border: 'none',
          backgroundColor: APPLE_COLORS.cardBackground
        }}>
          <Steps 
            current={current} 
            className="appointment-steps"
            direction="vertical"
            size="small"
          >
            <Step 
              title="选择科室" 
              description="请选择需要就诊的科室"
              icon={<SolutionOutlined />} 
            />
            <Step 
              title="选择医生" 
              description="请选择合适的医生"
              icon={<UserOutlined />} 
            />
            <Step 
              title="选择时间" 
              description="请选择就诊时间"
              icon={<CalendarOutlined />} 
            />
            <Step 
              title="信息填写" 
              description="请填写就诊信息"
              icon={<FileTextOutlined />} 
            />
          </Steps>
          <div style={{ margin: '32px 0', minHeight: 210 }}>
          {current === 0 && (
            <div>
              <h3 style={{ 
                marginBottom: 24, 
                fontSize: '22px', 
                fontWeight: 600,
                color: APPLE_COLORS.text
              }}>选择科室</h3>
              <List
                grid={{ gutter: 16, xs: 1, sm: 2, md: 3 }}
                dataSource={departments}
                renderItem={item => (
                  <List.Item>
                    <Card
                      onClick={() => setSelectedDepartment(item.id)}
                      className={`apple-card apple-hover-card ${selectedDepartment === item.id ? 'apple-selected-card' : ''}`}
                      style={{
                        cursor: "pointer",
                        borderRadius: 10,
                        border: selectedDepartment === item.id 
                          ? `2px solid ${APPLE_COLORS.primary}` 
                          : '1px solid transparent',
                        backgroundColor: APPLE_COLORS.cardBackground,
                        transition: 'all 0.3s ease'
                      }}
                      hoverable
                    >
                      <Space>
                        <SolutionOutlined style={{ fontSize: '20px', color: APPLE_COLORS.primary }} />
                        <span style={{ fontSize: '16px', fontWeight: 500, color: APPLE_COLORS.text }}>{item.name}</span>
                      </Space>
                    </Card>
                  </List.Item>
                )}
              />
            </div>
          )}
          {current === 1 && (
            <div>
              <h3 style={{ 
                marginBottom: 24, 
                fontSize: '22px', 
                fontWeight: 600,
                color: APPLE_COLORS.text
              }}>选择医生</h3>
              <List
                itemLayout="horizontal"
                dataSource={filteredDoctors}
                renderItem={item => (
                  <List.Item
                    onClick={() => setSelectedDoctor(item.id)}
                    className={`apple-card apple-hover-card ${selectedDoctor === item.id ? 'apple-selected-card' : ''}`}
                    style={{
                      cursor: 'pointer',
                      background: selectedDoctor === item.id ? APPLE_COLORS.primary + '10' : 'transparent',
                      borderRadius: 10,
                      margin: 4,
                      padding: 12,
                      transition: 'all 0.3s ease'
                    }}
                    actions={[
                      <Tag 
                        color={APPLE_COLORS.success} 
                        style={{ borderRadius: 12, padding: '2px 8px' }}
                      >
                        有{item.schedule[0].periods.filter(p=>p.available).length}个可预约时段
                      </Tag>
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<Avatar icon={<UserOutlined />} style={{ backgroundColor: APPLE_COLORS.primary }} />}
                      title={
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <span style={{ fontSize: '16px', fontWeight: 600, color: APPLE_COLORS.text }}>{item.name}</span>
                          <div style={{ 
                            marginLeft: 12,
                            padding: '2px 8px',
                            borderRadius: 12,
                            backgroundColor: APPLE_COLORS.secondary + '20',
                            color: APPLE_COLORS.secondary,
                            fontSize: '12px'
                          }}>
                            {item.title}
                          </div>
                        </div>
                      }
                      description={
                        <div style={{ fontSize: '14px', color: APPLE_COLORS.darkGray }}>
                          专科：{departments.find(dep => dep.id === item.departmentId)?.name}
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </div>
          )}

          {current === 2 && (
            <div>
              <h3 style={{ 
                marginBottom: 24, 
                fontSize: '22px', 
                fontWeight: 600,
                color: APPLE_COLORS.text
              }}>选择预约时间</h3>
              
              <div style={{ marginBottom: 24 }}>
                <h4 style={{ 
                  marginBottom: 16, 
                  fontSize: '18px',
                  fontWeight: 500,
                  color: APPLE_COLORS.textSecondary
                }}>选择日期</h4>
                <List
                  grid={{ gutter: 12, xs: 3, sm: 4, md: 5, lg: 7 }}
                  dataSource={selectedDoctor ? doctors.find(d => d.id === selectedDoctor)?.schedule || [] : []}
                  renderItem={(schedule) => (
                    <List.Item>
                      <Card
                        onClick={() => {
                          setSelectedDate(schedule.date);
                          setSelectedPeriod(null);
                          setSelectedTimeSlot(null);
                        }}
                        className={`apple-card apple-hover-card ${selectedDate === schedule.date ? 'apple-selected-card' : ''}`}
                        style={{
                          cursor: "pointer",
                          borderRadius: 10,
                          border: selectedDate === schedule.date 
                            ? `2px solid ${APPLE_COLORS.primary}` 
                            : '1px solid transparent',
                          backgroundColor: APPLE_COLORS.cardBackground,
                          transition: 'all 0.3s ease'
                        }}
                      >
                        <Space direction="vertical" align="center">
                          <CalendarOutlined style={{ fontSize: '20px', color: APPLE_COLORS.primary }} />
                          <div style={{ fontSize: '14px', fontWeight: selectedDate === schedule.date ? 600 : 400, color: selectedDate === schedule.date ? APPLE_COLORS.primary : APPLE_COLORS.text }}>{schedule.date}</div>
                          <Tag 
                            color={schedule.periods.some(p => p.available) ? APPLE_COLORS.success : APPLE_COLORS.darkGray} 
                            style={{ borderRadius: 12, padding: '2px 8px' }}
                          >
                            {schedule.periods.some(p => p.available) ? '可预约' : '已满'}
                          </Tag>
                        </Space>
                      </Card>
                    </List.Item>
                  )}
                />
              </div>
              
              {selectedDate && (
                <div style={{ marginBottom: 24 }}>
                  <h4 style={{ 
                    marginBottom: 16, 
                    fontSize: '18px',
                    fontWeight: 500,
                    color: APPLE_COLORS.textSecondary
                  }}>选择时段</h4>
                  <List
                    grid={{ gutter: 12, xs: 3 }}
                    dataSource={selectedDoctor 
                      ? doctors.find(d => d.id === selectedDoctor)?.schedule.find(s => s.date === selectedDate)?.periods || []
                      : []}
                    renderItem={(period) => (
                      <List.Item>
                        <Card
                          onClick={() => {
                            if (period.available) {
                              setSelectedPeriod(period.period);
                              setSelectedTimeSlot(null);
                            }
                          }}
                          className={`apple-card apple-hover-card ${selectedPeriod === period.period ? 'apple-selected-card' : ''}`}
                          style={{
                            cursor: period.available ? "pointer" : "not-allowed",
                            opacity: period.available ? 1 : 0.5,
                            borderRadius: 10,
                            border: selectedPeriod === period.period 
                              ? `2px solid ${APPLE_COLORS.primary}` 
                              : '1px solid transparent',
                            backgroundColor: APPLE_COLORS.cardBackground,
                            textAlign: 'center',
                            padding: '12px 0',
                            transition: 'all 0.3s ease'
                          }}
                        >
                          <div style={{ 
                            fontSize: '16px',
                            fontWeight: selectedPeriod === period.period ? 600 : 400,
                            color: selectedPeriod === period.period ? APPLE_COLORS.primary : APPLE_COLORS.text
                          }}>
                            {period.period === 'morning' ? '上午' : 
                             period.period === 'afternoon' ? '下午' : '晚上'}
                          </div>
                        </Card>
                      </List.Item>
                    )}
                  />
                </div>
              )}
              
              {selectedDate && selectedPeriod && (
                <div style={{ marginTop: 24 }}>
                  <h4 style={{ 
                    marginBottom: 16, 
                    fontSize: '18px',
                    fontWeight: 500,
                    color: APPLE_COLORS.textSecondary
                  }}>选择具体时间</h4>
                  <List
                    grid={{ gutter: 12, xs: 4, sm: 5 }}
                    dataSource={selectedDoctor
                      ? doctors.find(d => d.id === selectedDoctor)?.schedule
                          .find(s => s.date === selectedDate)?.periods
                          .find(p => p.period === selectedPeriod)?.timeSlots || []
                      : []}
                    renderItem={(time) => (
                      <List.Item>
                        <Card
                          onClick={() => setSelectedTimeSlot(time)}
                          className={`apple-card apple-hover-card ${selectedTimeSlot === time ? 'apple-selected-card' : ''}`}
                          style={{
                            cursor: "pointer",
                            borderRadius: 10,
                            border: selectedTimeSlot === time 
                              ? `2px solid ${APPLE_COLORS.primary}` 
                              : '1px solid transparent',
                            backgroundColor: APPLE_COLORS.cardBackground,
                            textAlign: 'center',
                            padding: '12px 0',
                            transition: 'all 0.3s ease'
                          }}
                        >
                          <div style={{ 
                            fontSize: '16px',
                            fontWeight: selectedTimeSlot === time ? 600 : 400,
                            color: selectedTimeSlot === time ? APPLE_COLORS.primary : APPLE_COLORS.text,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                          }}>
                            <ClockCircleOutlined style={{ marginRight: 4, fontSize: '14px' }} />
                            {time}
                          </div>
                        </Card>
                      </List.Item>
                    )}
                  />
                </div>
              )}
            </div>
          )}
          {current === 3 && (
            <div>
              <h3 style={{ 
                marginBottom: 24, 
                fontSize: '22px', 
                fontWeight: 600,
                color: APPLE_COLORS.text
              }}>填写挂号信息</h3>
              <Form
                form={form}
                layout="vertical"
                style={{ maxWidth: 600 }}
                initialValues={{
                  patientName: '',
                  patientId: '',
                  description: '',
                  symptoms: ''
                }}
              >
                <Form.Item
                  label="患者姓名"
                  name="patientName"
                  rules={[{ required: true, message: '请输入患者姓名' }]}
                  className="apple-form-item"
                >
                  <Input 
                    className="apple-input"
                    placeholder="请输入真实姓名" 
                    style={{
                      borderRadius: 10,
                      border: `1px solid ${APPLE_COLORS.mediumGray}`,
                      padding: '8px 12px',
                      fontSize: '16px'
                    }}
                  />
                </Form.Item>
                
                <Form.Item
                  label="身份证号"
                  name="patientId"
                  rules={[
                    { required: true, message: '请输入身份证号' },
                    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号码' }
                  ]}
                  className="apple-form-item"
                >
                  <Input 
                    className="apple-input"
                    placeholder="请输入18位身份证号码" 
                    style={{
                      borderRadius: 10,
                      border: `1px solid ${APPLE_COLORS.mediumGray}`,
                      padding: '8px 12px',
                      fontSize: '16px'
                    }}
                  />
                </Form.Item>
                
                <Form.Item
                  label="症状描述"
                  name="symptoms"
                  rules={[{ required: true, message: '请简要描述症状' }]}
                  className="apple-form-item"
                >
                  <Input.TextArea 
                    className="apple-textarea"
                    rows={3} 
                    placeholder="请简要描述您的症状" 
                    style={{
                      borderRadius: 10,
                      border: `1px solid ${APPLE_COLORS.mediumGray}`,
                      padding: '8px 12px',
                      fontSize: '16px'
                    }}
                  />
                </Form.Item>
                
                <Form.Item
                  label="病情说明"
                  name="description"
                  className="apple-form-item"
                >
                  <Input.TextArea 
                    className="apple-textarea"
                    rows={3} 
                    placeholder="如有其他病情说明，请在此补充" 
                    style={{
                      borderRadius: 10,
                      border: `1px solid ${APPLE_COLORS.mediumGray}`,
                      padding: '8px 12px',
                      fontSize: '16px'
                    }}
                  />
                </Form.Item>
                
                <div style={{ 
                  marginTop: 24, 
                  padding: 20, 
                  backgroundColor: APPLE_COLORS.lightGray, 
                  borderRadius: 12
                }}>
                  <h4 style={{ 
                    marginBottom: 16,
                    fontSize: '18px',
                    fontWeight: 600,
                    color: APPLE_COLORS.text
                  }}>预约信息确认</h4>
                  <div style={{ marginTop: 8 }}>
                    <p style={{ 
                      marginBottom: 8,
                      fontSize: '16px',
                      color: APPLE_COLORS.textSecondary
                    }}><strong>科室：</strong>{departments.find(d => d.id === selectedDepartment)?.name}</p>
                    <p style={{ 
                      marginBottom: 8,
                      fontSize: '16px',
                      color: APPLE_COLORS.textSecondary
                    }}><strong>医生：</strong>{doctors.find(d => d.id === selectedDoctor)?.name}</p>
                    <p style={{ 
                      marginBottom: 0,
                      fontSize: '16px',
                      color: APPLE_COLORS.textSecondary
                    }}><strong>时间：</strong>{selectedDate} {selectedPeriod === 'morning' ? '上午' : selectedPeriod === 'afternoon' ? '下午' : '晚上'} {selectedTimeSlot}</p>
                  </div>
                </div>
              </Form>
            </div>
          )}
        </div>
          {current > 0 && (
            <Button 
              className="apple-button-secondary"
              style={{ 
                marginRight: 12,
                borderRadius: 20,
                padding: '8px 24px',
                fontSize: '16px',
                border: `1px solid ${APPLE_COLORS.primary}`,
                backgroundColor: 'transparent',
                color: APPLE_COLORS.primary
              }}
              onClick={() => setCurrent(prev => prev - 1)}
            >
              上一步
            </Button>
          )}
          {current < 3 ? (
            <Button 
              className="apple-button-primary"
              type="primary" 
              style={{
                borderRadius: 20,
                padding: '8px 24px',
                fontSize: '16px',
                backgroundColor: APPLE_COLORS.primary,
                borderColor: APPLE_COLORS.primary
              }}
              onClick={() => {
                // 直接实现下一步逻辑，避免函数调用的问题
                if (current === 0 && !selectedDepartment) {
                  message.warning("请选择科室"); return;
                }
                if (current === 1 && !selectedDoctor) {
                  message.warning("请选择医生"); return;
                }
                if (current === 2 && !(selectedDate && selectedPeriod && selectedTimeSlot)) {
                  message.warning("请选择预约时间"); return;
                }
                setCurrent(prev => prev + 1);
              }}
            >
              下一步
            </Button>
          ) : (
            <Button 
              className="apple-button-primary"
              type="primary" 
              style={{
                borderRadius: 20,
                padding: '8px 32px',
                fontSize: '16px',
                backgroundColor: APPLE_COLORS.primary,
                borderColor: APPLE_COLORS.primary
              }}
              onClick={async () => {
                try {
                  const values = await form.validateFields();
                  const appointmentData = {
                    ...values,
                    departmentId: selectedDepartment!,
                    doctorId: selectedDoctor!,
                    slot: {
                      date: selectedDate!,
                      period: selectedPeriod!,
                      time: selectedTimeSlot!,
                      doctorId: selectedDoctor!,
                      departmentId: selectedDepartment!
                    }
                  };
                  
                  console.log('预约数据提交:', appointmentData);
                  message.success("预约成功！您的预约号为：" + Date.now().toString().slice(-6));
                  
                  setTimeout(() => {
                    setCurrent(0);
                    setSelectedDepartment(null);
                    setSelectedDoctor(null);
                    setSelectedDate(null);
                    setSelectedPeriod(null);
                    setSelectedTimeSlot(null);
                    form.resetFields();
                  }, 2000);
                } catch (error) {
                  console.error('预约失败:', error);
                  message.error("预约失败，请重试");
                }
              }}
            >
              提交预约
            </Button>
          )}
        </Card>

        {/* 底部提示信息 */}
        <div style={{ 
          marginTop: 24, 
          textAlign: 'center',
          fontSize: '14px',
          color: APPLE_COLORS.darkGray
        }}>
          <p style={{ margin: 4 }}>• 请提前30分钟到达医院，凭预约号取号</p>
          <p style={{ margin: 4 }}>• 如需取消预约，请提前2小时操作</p>
          <p style={{ margin: 4 }}>• 预约咨询电话：400-123-4567</p>
        </div>
      </div>
    </Layout>
  );
};
export default RegisterAppointment;
